package standalone

import (
	"bufio"
	"context"
	"fmt"
	"fpga-vboard/logger"
	"os"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

type SerialTerm struct {
	isConnect bool
	ctx       context.Context
}

var serialTerm *SerialTerm

func StartSerialTerm(ctx context.Context) {
	serialTerm = &SerialTerm{
		isConnect: false,
		ctx:       ctx,
	}
	go serialTerm.Run()
}

func (s *SerialTerm) IsConnect() bool {
	return s.isConnect
}

func (s *SerialTerm) procInput(inputData ...interface{}) {
	line := inputData[0].(string)
	fmt.Print(line)
}

func (s *SerialTerm) Run() {
	logger.InfoLog("SerialTerm start")
	runtime.EventsEmit(s.ctx, "displayOutput", "waiting for connect...")
	runtime.EventsOn(s.ctx, "displayInput", s.procInput)
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		runtime.EventsEmit(s.ctx, "displayOutput", scanner.Text())
	}
}
